import React, { Component } from 'react';
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheImage from '@/components/TheImage'
import { Modal, Form, Input, Pagination, Cascader, Alert, Button, Space,message } from 'antd'
import { apiGetGoodsInfoPage } from '@/request/activityManager'
import { apiGetGoodsClassifyTree } from '@/request/mallManagement'
import PropTypes from 'prop-types'
import { exportSheetTable } from '@/utils/exportTable'
import './style.less'
const { SHOW_CHILD } = Cascader;
class NoCanJoinGood extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            columns: [
                {
                    title: "序号",
                    key: "index",
                    dataIndex: "index",
                    render: (text, render, index) => {
                        return index + 1
                    }
                },
                {
                    title: "商品ID",
                    key: "goodsId",
                    width: 100,
                    dataIndex: "goodsId",
                },
                {
                    title: "商品名称",
                    key: "goodsName",
                    width: 100,
                    dataIndex: "goodsName",

                },
                {
                    title: "商品图片",
                    key: "goodsShowImages",
                    dataIndex: "goodsShowImages",
                    render: (text) => {
                        if (text) {
                            let str = text.split(',')[0]
                            return <div>
                                {
                                    text.split(',').map(item => <span style={{ marginRight: 10 }}><TheImage src={item} width={80} height={80} /></span>)
                                }
                            </div>

                        }
                    }

                }, {
                    title: "所属类目",
                    key: "goodsClassifyName",
                    dataIndex: "goodsClassifyName",
                    // render: (text) => {
                    //     return <div>{text}</div>
                    //     return <Cascader showCheckedStrategy={SHOW_CHILD} disabled={true} options={this.state.classifyList} value={[text.split(',')]} />
                    // }
                },
                {
                    title: "商品原价",
                    key: "originalPrice",
                    dataIndex: "originalPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.originalPrice || 0} />

                    },

                },
                {
                    title: "商品现价",
                    key: "currentPrice",
                    dataIndex: "currentPrice",
                    render: (text, render) => {
                        return <React.$Price price={render.currentPrice || 0} />

                    },

                }, {
                    title: "商品状态",
                    key: "goodsStatus",
                    dataIndex: "goodsStatus",
                    render: (text, render) => {
                        return text === 'Y' ? '上架' : '下架'

                    },

                },
                {
                    title: "上次操作时间",
                    key: "updateTime",
                    dataIndex: "updateTime",

                },
                {
                    title: "操作",
                    fixed: 'right',
                    render: (text, render) => {
                        return <TheButton onClick={() => this.delGoods(text)}>删除</TheButton>

                    },
                },
            ],
            dataSource: [],
            blackDataSource: [],
            isModalVisible: false,
            pageNo: 1,
            pageSize: 10,
            totalCount: 0,
            searchForm: {
                goodsName: '',
                goodsId: ''
            },
            classifyList: [],
            selectedRowKeys: [],
            selectedRows: [],
            hasKeys: [],
            alertType: '',
            importInfo: {}
        }
    }
    componentDidMount() {
        console.log(this.props, '[[[[');
        this.setState({
            selectedRowKeys: this.props.blackGoodsKey,
            blackDataSource: this.props.blackGoods,
            selectedRows: this.props.blackGoods,
        })
        this.getData()
    }
    componentDidUpdate(nextProps) {
        if (nextProps.blackGoodsKey.length !== this.props.blackGoodsKey.length) {

            this.setState({
                selectedRowKeys: this.props.blackGoodsKey,
                // blackDataSource: this.props.blackGoods,
                // selectedRows: this.props.blackGoods,
            })
        }
    }
    reset(fn) {

        this.setState({
            searchForm: {
                goodsName: '',
                goodsId: ''
            },
            pageNo: 1,
            blackDataSource: [],
            alertType: '',
            selectedRowKeys: [],
            selectedRows: [],
        }, () => fn && fn())
        console.log(this.state)

    }
    // 获取商品列表
    async getData() {
        const { goodsName, goodsId } = this.state.searchForm
        let res = await apiGetGoodsInfoPage({ pageNo: this.state.pageNo, pageSize: this.state.pageSize, goodsName: goodsName ? goodsName : '', goodsId: goodsId ? goodsId : '', storeStatus: 'Y', goodsStatus: 'Y', reviewStatus: 'T' })
        if (res.code === 0) {
            this.setState({
                dataSource: [],
                totalCount: res.totalCount
            }, () => this.setState({
                dataSource: res.data,
            }))
        } else {
            React.$message({
                type: 'error',
                content: res.codeMessage
            })
        }
    }
    // 获取类目
    getClassifyList = async () => {
        const res = await apiGetGoodsClassifyTree()
        if (res.code === 0) {
            this.setState({
                classifyList: res.data.map((v) => {
                    return {
                        value: v.value,
                        label: v.label,
                        children: v.children.length > 0 ? v.children : []
                    }
                })
            })
        }
    }
    delGoods(row) {
        let keys = []
        this.state.blackDataSource = this.state.blackDataSource.filter(item => {
            if (item.goodsId !== row.goodsId) {
                keys.push(item.goodsId)
                return item
            }
        })
        this.setState({
            blackDataSource: this.state.blackDataSource,
            selectedRows: this.state.blackDataSource,
            selectedRowKeys: keys
        }, () => {
            this.props.getBlackGoods(this.state.selectedRowKeys)
        })
    }

    //商品批量导入
    async importGoods(e) {
        let formData = new FormData()
        formData.append('file', e.target.files[0])
        e.target.value = ""
        fetch(React.$BaseUrl +  '/admin/platformActivitySheet/excelBlacklistImport', {
            method: "post",
            headers: {
                RSnetToken: sessionStorage.getItem('RSnetToken')
            },
            body: formData,
        })
            .then((res) => {
                // this.setState({
                //     alertType:'success'
                // })
                res.json().then(result => {
                    console.log(result, 'ress')
                    if (result.code === 0) {
                        const { code, data, codeMessage } = result.data
                        if (code === 0) {
                            const keys = data.map(item => item.goodsId)
                            this.setState({
                                selectedRowKeys: keys,
                                blackDataSource: data,
                                selectedRows: data,
                                alertType: 'success',
                                importInfo: {
                                    title: '导入成功！',
                                    data: data,
                                    message: codeMessage
                                }
                            }, () => this.props.getBlackGoods(keys))
                            setTimeout(() => {
                                this.setState({
                                    alertType: ''
                                })
                            }, 3000)
                        } else if (code == 5000) {
                            this.setState({
                                alertType: 'error',
                                importInfo: {
                                    title: '导入失败！',
                                    data: data,
                                    message: codeMessage
                                }
                            })

                        } else {
                            message.error(codeMessage)
                        }

                    }else{
                        message.error(result.codeMessage)
                      }
                })
            })
            .catch((res) => {
                React.$message({
                    type: 'error',
                    content: '导入失败'
                })
            })
            .finally(() => {

            });

    }
    // 选择不参加商品弹框
    goChoose() {
        this.setState({
            isModalVisible: true,
        })
    }
    // 选择商品保存
    handleOk = () => {
        this.setState({
            blackDataSource: [],
            isModalVisible: false
        }, () => {
            const keys = this.state.selectedRows.map(item => item.goodsId)
            this.setState({
                blackDataSource: this.state.selectedRows,
                selectedRowKeys: keys
            })
            this.props.getBlackGoods(keys)
        })
    }
    // 选择商品取消
    handleCancel = () => {
        this.setState({
            isModalVisible: false,
            selectedRowKeys: []
        }, () => {
            this.setState({
                selectedRowKeys: this.state.blackDataSource.map(item => item.goodsId)
            })
        })
    }
    //批量勾选
    onSelect = (record, selected, selectedRows, nativeEvent) => {

        let keys = this.state.selectedRowKeys
        console.log(keys, 'a;;', this.state.selectedRows)

        if (selected) {
            keys.push(record.goodsId)
            this.state.selectedRows.push(record)
        } else {
            this.state.selectedRows.splice(keys.indexOf(record.goodsId), 1)
            keys.splice(keys.indexOf(record.goodsId), 1)
        }
        keys = Array.from(new Set(keys))
        this.setState({
            selectedRowKeys: keys,
            selectedRows: this.state.selectedRows
        })
    }
    onSelectAll = (selected, rows, newRow) => {


        console.log(selected, 'a;;', rows)
        let keys = this.state.selectedRowKeys
        if (selected) {
            newRow.forEach(item => {
                keys.push(item.goodsId)
                this.state.selectedRows.push(item)
            })
        } else {
            newRow.forEach(item => {
                if (keys.indexOf(item.goodsId) > -1)
                    this.state.selectedRows.splice(keys.indexOf(item.goodsId), 1)
                keys.splice(keys.indexOf(item.goodsId), 1)
            })
        }
        keys = Array.from(new Set(keys))
        this.setState({
            selectedRowKeys: keys,
            selectedRows: this.state.selectedRows
        })
    }
    // 弹框分页
    pageChange(e) {

        this.setState({ pageNo: e }, () => {
            this.getData()
        })

    }
    // 弹框搜索
    searchGoods() {
        const values = this.formRef.current.getFieldsValue()
        this.setState({
            searchForm: {
                goodsId: values.goodsId,
                goodsName: values.goodsName
            },
            pageNo: 1
        }, () => this.getData())
    }
    // 弹框重置
    resetForm() {
        this.formRef.current.resetFields()
        this.setState({
            searchForm: {
                goodsId: '',
                goodsName: ''
            }
        }, () => this.getData())
    }
    onAlertClose() {
        this.setState({
            alertType: ''
        })
    }
    downloadExcel = () => {
        let tH_data = [
            { prop: 'goodsId', title: '商品ID(必填)' },
            { prop: 'goodsName', title: '商品名称(非必填)' },
            { prop: 'checkState', title: '校验' },
            { prop: 'checkMsg', title: '说明' }
        ]
        let tB_data = this.state.importInfo.data.map(item => {
            return {
                goodsId: item.goodsId,
                goodsName: item.goodsName,
                checkState: item.checkState,
                checkMsg: item.checkMsg,
            }
        })
        exportSheetTable({
            fileName: `活动商品黑名单报错数据`, tH_data: tH_data, tB_data: tB_data, isSheet: true, merge: false
        })
    }
    render() {
        const { columns, dataSource, isModalVisible, pageNo, importInfo, alertType, totalCount, blackDataSource, classifyList, selectedRowKeys } = this.state
        const { whiteGoodsKey } = this.props
        const columns11 = columns.slice(0, columns.length - 1)
        const rowSelection = {
            getCheckboxProps: (record) => {
                return {
                    disabled: whiteGoodsKey.includes(record.goodsId),
                }
            },
            selectedRowKeys,
            onSelect: this.onSelect,
            onSelectAll: this.onSelectAll
        };
        return (
            <div className='noCanJoinGood'>
                <div className='btnList'>
                    <TheButton type="default" size="middle" className="goodsImport" onClick={() => this.goChoose()}>选择商品</TheButton>
                    <TheButton type="default" size="middle" className="goodsImport" >
                        <input type="file" className="importBtn" onChange={(e) => this.importGoods(e)} />
                        批量导入
                    </TheButton>
                    <TheButton type="link" size="middle" className="downloadDemo" >
                        <a href="https://hqmimage.oss-cn-beijing.aliyuncs.com/%E6%B4%BB%E5%8A%A8%E9%BB%91%E5%90%8D%E5%8D%95%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx" download={'商品导入模板'}>下载导入文件模板</a>
                        {/* <span>说明：导入为全量导入，且会覆盖原商品数据！</span> */}
                    </TheButton>
                </div>
                <TheTable
                    scroll={{ x: "max-content", y: '43vh' }}
                    columns={columns}
                    dataSource={blackDataSource}
                />
                <Modal
                    width={'90%'}
                    title={'选择商品'} visible={isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form
                        layout={'inline'}
                        ref={this.formRef}
                    >
                        <Form.Item
                            name="goodsName"
                        >
                            <Input
                                placeholder="商品名称"
                                style={{ width: 300 }}
                            />
                        </Form.Item>
                        <Form.Item
                            name="goodsId"
                        >
                            <Input
                                placeholder="商品ID"
                                style={{ width: 300 }}
                            />
                        </Form.Item>
                        <Form.Item>
                            <TheButton size="middle" className="goodsImport" type="primary" onClick={() => this.searchGoods()}>查询</TheButton>
                            <TheButton size="middle" type="default" onClick={() => this.resetForm()}>重置</TheButton>
                        </Form.Item>

                    </Form>
                    <TheTable
                        style={{ margin: '10px 0' }}
                        scroll={{ x: "max-content", y: '57vh' }}
                        columns={columns11}
                        dataSource={dataSource}
                        rowSelection={rowSelection}
                        rowKey={(record) => record.goodsId}
                    />
                    <Pagination style={{ textAlign: 'right' }} size="small" current={pageNo} total={totalCount} showSizeChanger={false} onChange={this.pageChange.bind(this)} />

                </Modal>
                {
                    alertType && <div style={{ width: '100vw', height: '100vh', position: 'fixed', left: 0, top: 0, zIndex: 9999 }}>
                        <Alert
                            style={{ margin: '100px auto', width: 500 }}
                            message={importInfo.title}
                            showIcon
                            description={importInfo.message}
                            type={alertType}
                            closable
                            onClose={() => this.onAlertClose()}
                            action={
                                alertType === 'error' && <Space direction="vertical">
                                    <Button size="small" type="primary" onClick={this.downloadExcel}>
                                        下载文件
                                    </Button>
                                </Space>
                            }
                        />
                    </div>
                }

            </div>
        );
    }
}
NoCanJoinGood.propTypes = {
    blackGoods: PropTypes.array,
    blackGoodsKey: PropTypes.array,
    whiteGoodsKey: PropTypes.array,
}
NoCanJoinGood.defaultProps = {
    blackGoods: [],
    blackGoodsKey: [],
    whiteGoodsKey: [],
}
export default NoCanJoinGood